package com.rmi.spring.client;

import java.lang.reflect.Field;

import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.rmi.anno.client.Remote;
import com.rmi.registry.zk.ZooKeeperServiceDiscovery;



public class RemoteBeanPostProcessor implements BeanPostProcessor,ApplicationContextAware{

	private ApplicationContext applicationContext;
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		Class<?> objClz;
		if (AopUtils.isAopProxy(bean)) {
			objClz = AopUtils.getTargetClass(bean);
		} else {
			objClz = bean.getClass();
		}
		try {
			for (Field field : objClz.getDeclaredFields()) {
				// 判断该字段是否有 Remote 注解
				if (field.isAnnotationPresent(Remote.class)) {
					//这里需要一个查找服务的接口，否则无法完成多server下的接口映射
					ZooKeeperServiceDiscovery discovery = applicationContext.getBean(ZooKeeperServiceDiscovery.class);
					String serviceUrl=discovery.discover(field.getType().getName());
					System.out.println("serviceUrl=="+serviceUrl);
					RemoteFactoryBean remoteFactoryBean = new RemoteFactoryBean(field.getType(),serviceUrl);
					Object rpcReference = remoteFactoryBean.getObject();
					field.setAccessible(true);
					field.set(bean, rpcReference);
				}
			}
		} catch (Exception e) {
			throw new BeanCreationException(beanName, e);
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		return bean;
	}
	

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
